//import static com.sun.xml.internal.ws.api.message.Packet.Status.Response;

import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.*;

/**
 * Created by dell on 2017/8/14.
 */
public class OkGetPicture {
    public static void main(String[] args) throws IOException {
        getManyPicture("http://img.mmjpg.com/2016/", 716,
                1100, 1, 40, ".jpg", "妹子图", 100);
    }

    //下载多张图片
    public static void getManyPicture(String net, int startPage, int destPage, int startPicture, int destPicture,
                                      String type, String pictureName, int pictureNum) throws IOException {
        int count = 0;
        for (int j = startPage; j < destPage; j++) {
            for (int i = startPicture; i < destPicture; i++) {
                int k = new OkGetPicture().loadPictureToFile(net, j, i, type, j, i, pictureName);
                if (k == 0) {
                    break;
                }
                count++;
                if (count == pictureNum) {
                    return;
                }

            }

        }
    }

    public int loadPictureToFile(String url, int page, int startNum, String type, int j, int i, String pictureName) throws IOException {
        try {
            OkHttpClient okHttpClient = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url + page + "/" + startNum + type)
                    .addHeader("Referer", url + page)
                    .build();
            //final Call call = okHttpClient.newCall(request);
            String net = url + j + "/" + i + type;
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                System.out.println(response.code());
            } else {
                response.body().close();
                //throw new IOException("Unexpected code"+response);
            }
            //call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//            }
//            @Override
//            public void onResponse(Response response) throws IOException {
            //for (int i=startNum;i<7;i++) {
            InputStream is = null;
            //byte[] buf = new byte[2048];
            //int len = 0;
            try {
                is = response.body().byteStream();
                byte[] b = readInputStream(is);
                response.body().close();
                if (null != b & b.length > 0) {
                    System.out.println("读取到：" + b.length + " 字节");
                    String fileName = pictureName + j + "_" + i + type;
                    writeImageToDisk(b, fileName);
                    System.out.println("address " + net + " is loaded");
                } else {
                    System.out.println("没有从该链接获得内容");
                }
//                        File file = new File(destFileDir, pictureName + j+"_"+i+ loadPictureToFile);
//                        fos = new FileOutputStream(file);
//                        if (null!=fos){
//                        while ((len = is.read(buf)) != -1) {
//                            fos.write(buf, 0, len);
//                            System.out.println("address:"+net+"loaded");
//                        }
//                    fos.flush();
                //如果下载文件成功，第一个参数为文件的绝对路径

            } catch (Exception e) {
                //sendFailedStringCallback(response.request(), e, callback);
                System.out.println("失败");
                return 0;
            } finally {
                try {
                    if (is != null) is.close();
                } catch (IOException e) {
                }
            }
        } catch (Exception e) {
            System.out.println("下一页");
            return 0;
        }
        return 1;
    }
    //        });
//    }

    public static void writeImageToDisk(byte[] img, String fileName) {
        try {
            File file = new File("F:/图片/" + fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("图片已经写入到F盘");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}

